<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总的记录数据:{{total}}条</span>
        </template>
         <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="importExcel">导入excel</el-button>
          <el-button v-allow="'exportTo_excel'" type="danger" size="small" @click="exportToExcel">导出excel</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

        <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index"/>
          <el-table-column label="姓名" prop="username"/>
          <el-table-column label="用户头像">
            <template #default="{ row }">
                    <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber"/>
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{formmatHirType(row.formOfEmployment)}}

            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName"/>
          <el-table-column label="入职时间" prop="timeOfEntry"/>
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
               @size-change="handleSizeChange"
               @current-change="handleCurrentChange"
               :current-page="page"
               :page-sizes="[2, 5, 10, 30]"
               :page-size="size"
               layout="total, sizes, prev, pager, next, jumper"
               :total="total">
    </el-pagination>
        </el-row>
      </el-card>
      <el-dialog 
      title="新增员工" 
      :visible.sync="showDialog"
      @close="hClose"
      >
        <addOrEdit
        ref="myEmp"
         @success="hSuccess"/>
      </el-dialog>
        <el-dialog 
      title="分配角色" 
      :visible.sync="assignShowDialog"
      >
       <assignRole
       v-if="assignShowDialog" 
       :user-id="userId"
       @success="assignShowDialog=false"
       />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList,delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import addOrEdit from './empDialog.vue'
import assignRole from './assignRole.vue'

// const hireType = {}
//  employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
//  })

 const hireType = employeesEnum.hireType.reduce((acc,item)=>{
  acc[item.id] = item.value 
  return acc
 },{})

 console.log(employeesEnum.hireType,'employeesEnum');
export default {
  components:{
    addOrEdit,
    assignRole
  },
  data(){
   return {
    assignShowDialog:false,
    showDialog:false,
    list:[],
    page:1, // 页码值
    size:5, // 每页显示的条数
    total:0,
    userId:''
   }
  },
   created(){
      this.loadEmployeeList()
   },
   methods: {
    hAssignRole(id){
      this.userId = id
      this.assignShowDialog = true
    },
    exportToExcel(){
      const {tHeader,result} = this.formatToExcel(this.list)
      console.log(tHeader,'tHeader')
      console.log(result,'result')
   import('@/vendor/Export2Excel').then(excel => {
        // 2. 格式化数据
        // export_json_to_excel将格式化的数据写入到excel
        excel.export_json_to_excel({
          header: tHeader,
          data: result,
          filename: '', // 设置文件的名称  ''
          autoWidth: true, // 宽度自适应   true
          bookType: 'xlsx' // 导入的文件类型  'xlsx'
        })
        })
    },
    formatToExcel(list) {
            //    中引文的映射对象
            const mapInfo = {
                'id': '编号',
                'password': '密码',
                'mobile': '手机号',
                'username': '姓名',
                'timeOfEntry': '入职日期',
                'formOfEmployment': '聘用形式',
                'correctionTime': '转正日期',
                'workNumber': '工号',
                'departmentName': '部门',
                'staffPhoto': '头像地址'
            }

            // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]
            // 1 生成表头
            // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
            const one = list[0]
            if (!one) return
            const tHeader = Object.keys(one).map(en_key => {
                return mapInfo[en_key]
            })
            // 2 生成表的内容data
            const result = list.map(item => {
                return Object.values(item)
            })
           return  {tHeader,result}
           
        },
        importExcel(){
          this.$router.push('./import')
        },
    hDel(id){
      this.$confirm('确认删除吗?').then(async()=>{
        const res = await delEmployee(id)
        if(this.list.length === 1){
          this.page--
          if(this.page <= 0) {
            this.page = 1
          }
        }
        if(res.code === 10000) {
          this.loadEmployeeList()
        }
      }).catch(error => console.log(error))
    },
    hClose(){
      this.$refs.myEmp.resetForm()
    },
    hSuccess(){
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.showDialog = false
      this.loadEmployeeList()
    },
    formmatHirType(value) {
         return hireType[value] || '未知'
    },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`)
        this.page = 1
        this.size = val
      this.loadEmployeeList()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`)
        this.page = val
        this.loadEmployeeList()
      },
    async loadEmployeeList(){
      try {
        const res = await getEmployeeList(this.page,this.size)
        console.log(res,'getEmployeeList')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
   },
}
</script>
